from django.shortcuts import render, redirect,HttpResponse

from myapp.utils.Pagination import Pagination
from myapp import models

def depart_list(request):
    """部门列表"""
    # 使用分页组件
    data_list = models.Department.objects.all()#拿到原数据
    part_page = Pagination(request,query_set=data_list) #实例化分页类
    departs = part_page.data_queryset
    page_str = part_page.html() # 得到分页标签

    return render(request, 'depart_list.html', {'departs': departs,'page_str':page_str})


def depart_add(request):
    """部门添加功能"""
    if request.method == 'GET':
        return render(request, 'depart_add.html')
    elif request.method == 'POST':
        name = request.POST.get('name')
        if name == '':
            print('添加的部门为空，请重新输入')
            return render(request, 'depart_add.html')
        print('添加的部门为:' + name)
        models.Department.objects.create(title=name)
        return redirect('/depart/list/')


def depart_del(request):
    """删除用户"""
    del_choice = request.GET.get('nid')
    print('删除了部门id' + del_choice)
    models.Department.objects.filter(id=del_choice).delete()  # 删除id为当前选项的
    return redirect('/depart/list/')


def depart_update(request, nid):
    """更新部门"""
    if request.method == 'GET':
        departs = models.Department.objects.filter(id=nid)
        return render(request, 'depart_update.html', {'data_list': departs})
    else:
        name = request.POST.get('name')
        models.Department.objects.filter(id=nid).update(title=name)
        return redirect('/depart/list/')

def depart_excel(request):
    # 1.获取用户上传文件对象
    file_obj = request.FILES.get("exfile")
    # 2.将文件对象用openpyxl打开并读取
    from openpyxl import load_workbook
    wb = load_workbook(file_obj)# 实例化对象
    print(wb)
    sheet= wb.worksheets[0] #worksheets会返回一个列表，列表里每个元素是一个工作簿类对象，打开第1个sheet工作簿
    # 循环读取每行内容
    for i in sheet.iter_rows(min_row=2): # 取出每个i是一个元组，元组里的元素为一个单元格对象
        print(i[0].value)
        exist = models.Department.objects.filter(title=i[0].value).exists()
        if not exist:# 不存在的才存
             models.Department.objects.create(title=i[0].value)
    return redirect('/depart/list')